<?php

namespace System;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\XmlFileLoader;

/**
 * Description of FrontController
 *
 * @author nofear
 */
class FrontController {

    private $controller;
    private $currentRouteName;
    private $method;
    private $Router;
    private $params;
    public static $_instance;
    
    private function __construct() {
        
    }
    
    public function getRouter() {
        return $this->Router;
    }

    public function setRouter($Router) {
        $this->Router = $Router;
    }
    
    public function dispatch() {
        if ( !$this->Router ) {
            throw new \Exception('No valid router found!', 500);
        }
        
        $uri = $this->Router->getPathInfo();
  
        $Config = \Shared\Application::getInstance()->getConfig();
        $loader = new XmlFileLoader(new FileLocator(array($Config->getConfigFolder())));
        $routeCollection = $loader->load('routes.xml');
        
        $matcher = new \Symfony\Component\Routing\Matcher\UrlMatcher($routeCollection, new \Symfony\Component\Routing\RequestContext());
        $match = $matcher->match($uri);
        
        if ( $match ) {
            $this->Controller = new $match['_controller'];
            $method = $match['_method'];
            $this->currentRouteName = $match['_route'];
            unset($match['_controller']);
            unset($match['_method']);
            unset($match['_route']);
            if ($this->Controller instanceof \Shared\Service) {
                $response = call_user_func_array(array($this->Controller, $method), $match);
                $response->send();
            } else {
                call_user_func_array(array($this->Controller, $method), $match);
            }
        } else {
            \Shared\Application::getInstance()->createNotFound();
        }
    }
    
    public function getHtml() {
        if ($this->Controller instanceof \Shared\Service) {
//            exit();
        } else {
            return $this->Controller->render();
        }
    }
    
    public function getCurrentRouteName() {
        return $this->currentRouteName;
    }

    public function setCurrentRouteName($currentRouteName) {
        $this->currentRouteName = $currentRouteName;
    }
    
    public function getController() {
        return $this->controller;
    }

    public function getMethod() {
        return $this->method;
    }

    public function getParams() {
        return $this->params;
    }
    
    /**
     * 
     * @return \Shared\FrontController
     */
    public static function getInstance() {
        if ( !self::$_instance ) {
            self::$_instance = new self;
        }
        
        return self::$_instance;
    }
}
